import React from 'react'
// ===================================================================== Temp
import SubmitForm from '#cpt/temp/SubmitForm'
import Controls from '#cpt/temp/Controls'
// ===================================================================== global declare
const { $fn, $http, $Lazy, globalConfig:{COVIDUrl} } = window
// ===================================================================== $Lazy
const Printer 			= $Lazy.hook(()=>import('#private/printer'))
const Form 				= $Lazy.hook(()=>import('@antd/form/layout/form'))
const confirm 			= $Lazy.file(()=>import('@antd/confirm'))
const FormItem 			= $Lazy.load(()=>import('#cpt/form/submit-item'))
const BtnGroup 			= $Lazy.load(()=>import('#tp/btn-group'))
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		selectedKeys:[],
		selectedRows:[],
		// 搜索表单列表
		formData : [
			{ label: '板号',	name: 'boardNo',		width: '60',	disabled:true,	p:' ',
				btn: { label: '换板', 	disabled:false,	onClick: ()=>{ 
					this.getBoard() 
					this.clearBoard()
					this.formRef1.reset()
				} },
			},
		],
		selectIndex: '',// 当前选中的表格index(0-95)
		print:false,
		tableNum: new Array(96).fill('')
	}
	negativeIndex = 0	// 阴性初始值
	positiveIndex = 0	// 阳性初始值
	boardData = {}	// 板子信息
	kindName = ''	// 项目名称
	bordSpec = []
	
	componentDidMount(){
		this.getKindName()
	}
	
	getKindName = () => {
		$http.pull(null, COVIDUrl+'settings/query', { param:{page_num:1000,page:1 }}).then(data=>{
			if($fn.hasArray(data)){
				const kindItem = data.find(v => v.settingsCode === 'ConvidProjectName')
				this.kindName = kindItem ? kindItem.settingsValue : ''
			}
		})
	}
	
	getBoard = () => {	// 获取板号
		$http.pull(null,COVIDUrl+'board/getBoard').then(data=>{
			this.formRef.setValue({boardNo:data.boardNo})
			this.boardData = data
		})
	}
	
	setBoardValue = (tableNum,rows) => {
		this.setState({tableNum})
		let {negative, positive, deviceInfo, remark} = rows
		negative = negative ? JSON.parse(negative) : {}
		positive = positive ? JSON.parse(positive) : {}
		deviceInfo = deviceInfo ? JSON.parse(deviceInfo) : {}
		const formData = {...negative,...positive,...deviceInfo,remark}
		this.formRef1.reset()
		this.formRef1.setValue(formData)
	}
	
	controls1 = () => {
		return [
			Controls.click.call(this, '重置板号', ()=> {
				$http.pull(null,COVIDUrl+'board/createBoard').then(data=>{
					$fn.msg.success('重置板号成功')
					if($fn.hasObject(data)){
						this.formRef.setValue({boardNo:data.boardNo})
						this.boardData = data
						this.clearBoard()
						this.formRef1.reset()
					}
				})
			}),
		]
	}
	
	controls = () => {
		const {selectIndex, tableNum} = this.state
		const validNum = tableNum.filter(v=>$fn.hasObject(v))
		return [
			Controls.click.call(this, '插入阴性质控', ()=> {
				const {hospId} = this.props.getValue()
				const { id, boardNo } = this.boardData
				if(!hospId){
					return $fn.msg.warning('医院必填')
				}else if(hospId === '无'){
					return $fn.msg.warning('该医院不存在，请先添加医院')
				}
				if(!$fn.hasObject(this.boardData)){
					return $fn.msg.warning('请先获取版号')
				}
				const tableArr = this.state.tableNum
				if(selectIndex === ''){
					const index = this.state.tableNum.findIndex((v1,i1) => !$fn.hasObject(v1) )
					if(index >= 96 || index ===-1){
						return $fn.msg.warning('该板号已无位置')
					}else{
						tableArr[index] = {dtype:1, negaI:++this.negativeIndex,
							board_id:id, board_no:boardNo,
							exp_no:100+(index+1), spec_code:this.negativeIndex>9?'N'+this.negativeIndex:'N0'+this.negativeIndex,
							sort:index+1, hosp_id: hospId
						}
					}
				}else{
					if($fn.hasObject(this.state.tableNum[selectIndex])){
						return $fn.msg.warning('该位置已添加')
					}
					tableArr[selectIndex] = {dtype:1, negaI:++this.negativeIndex,
						board_id:id, board_no:boardNo,
						exp_no:100+(selectIndex+1), spec_code:this.negativeIndex>9?'N'+this.negativeIndex:'N0'+this.negativeIndex,
						sort:selectIndex+1, hosp_id: hospId
					}
				}
				this.setState({selectIndex:'',tableNum:tableArr})
			}),
			Controls.click.call(this, '插入阳性质控', ()=> {
				const {hospId} = this.props.getValue()
				const { id, boardNo } = this.boardData
				if(!hospId){
					return $fn.msg.warning('医院必填')
				}else if(hospId === '无'){
					return $fn.msg.warning('该医院不存在，请先添加医院')
				}
				if(!$fn.hasObject(this.boardData)){
					return $fn.msg.warning('请先获取版号')
				}
				const tableArr = this.state.tableNum
				if(selectIndex === ''){
					const index = this.state.tableNum.findIndex((v1,i1) => !$fn.hasObject(v1) )
					if(index > 96 || index ===-1){
						return $fn.msg.warning('该板号已无位置')
					}else{
						this.positiveIndex++
						tableArr[index] = {dtype:2,
							board_id:id, board_no:boardNo,
							exp_no:200+(index+1), spec_code:this.positiveIndex>9?'P'+this.positiveIndex:'P0'+this.positiveIndex,
							sort:index+1, hosp_id: hospId
						}
					}
				}else{
					if($fn.hasObject(this.state.tableNum[selectIndex])){
						return $fn.msg.warning('该位置已添加')
					}
					this.positiveIndex++
					tableArr[selectIndex] = {dtype:2,
						board_id:id, board_no:boardNo,
						exp_no:200+(selectIndex+1), spec_code:this.positiveIndex>9?'P'+this.positiveIndex:'P0'+this.positiveIndex,
						sort:selectIndex+1, hosp_id: hospId
					}
				}
				this.setState({selectIndex:'',tableNum:tableArr})
			}),
			Controls.click.call(this, '删除实验号', ()=> {
				const {selectIndex,tableNum} = this.state
				const tableArr = tableNum
				if(+tableNum[selectIndex].dtype === 0){
					this.bordSpec.forEach((v,i)=>{
						if(tableNum[selectIndex].spec_code === v){
							this.bordSpec.splice(i,1)
						}
					})
				}
				tableArr[selectIndex] = ''
				this.setState({selectIndex:'',tableNum:tableArr})
			}, {disabled:(selectIndex ==='' || !$fn.hasObject(this.state.tableNum[selectIndex]))}),
			Controls.click.call(this, '整板重置', ()=> {
				this.clearBoard()
				this.formRef1.reset()
			}),
			Controls.click.call(this, '整板保存', ()=> {
				const {is_print} = this.props.getValue()
				const {tableNum} = this.state
				let codeParam = []
				let boardParam = []
				let specArr = []
				tableNum.forEach((v,i) =>{
					if($fn.hasObject(v) && v.dtype === 0){
						specArr.push(v.spec_code)
					}
				})
				if($fn.hasArray(specArr)){		// 查看重复条码并提示
					let RepArr = [];
					specArr.forEach((v)=>{
						if(specArr.indexOf(v) !== specArr.lastIndexOf(v) && RepArr.indexOf(v) === -1){
							RepArr.push(v)
						}
					})
					if($fn.hasArray(RepArr)){
						return $fn.msg.warning(`条码【${RepArr.join(',')}】重复录入,请检查`,3)
					}
				}
				$http.pull(null,COVIDUrl+'codeinfo/checkSpecCode',{param:{spec_code:specArr.join(',')}}).then(data=>{
					tableNum.forEach((v,i) =>{
						if($fn.hasObject(v)){
							boardParam.push({ board_id: v.board_id, sort: v.sort, board_no: v.board_no,
								exp_no: v.exp_no, spec_code: v.spec_code, dtype: v.dtype,
							})
							if(v.dtype === 0){
								codeParam.push({ spec_code: v.spec_code, experiment_num: v.board_no + '-' +v.exp_no,
									board_no: v.board_no, status: v.status, hosp_id: v.hosp_id, remark: v.remark,
								})
							}
						}
					})
					$http.submit(null, COVIDUrl+'BoardInfo/createlist', { param: {DataList: boardParam}, loadingText:'添加板子中'}).then(data => {
						$http.submit(null, COVIDUrl+'codeinfo/createlist', { param: {CodeData: codeParam}, loadingText:'添加标本中'}).then(data => {
							$fn.msg.success('录入成功')
							this.saveOtherInfo()
							if(is_print){
								this.printData()
							}
							this.boardData = {}
							this.formRef.setValue({boardNo:''})
							this.clearBoard()
							this.formRef1.reset()
						})
					})
				}).catch(({data})=>{
					if(data){
						const exitSpec = data.split(',')
						const tableArr = tableNum
						tableArr.forEach((v,i)=>{		// 添加背景色
							if(exitSpec.includes(v.spec_code+'')){
								tableArr[i].warnbc = true
							}
						})
						this.setState({tableNum:tableArr},()=>{		// 确认是否删除
							confirm.then( f => {
								f({
									msg: `条码【${data}】已存在,是否确认从当前板子删除？`,
									width: 500,
									onOk: async close => {
										tableArr.forEach((v,i)=>{
											if(exitSpec.includes(v.spec_code+'')){
												tableArr[i] = ''
											}
										})
										this.setState({tableNum:tableArr},()=>{
											this.bordSpec = []
											this.state.tableNum.forEach(v=>{
												if($fn.hasObject(v) && v.dtype === 0){
													this.bordSpec.push(v.spec_code)
												}
											})
										})
										close()
										$fn.msg.success('删除成功')
									}
								})
							})
						})
						
					}
				})
				
			}, {disabled:!validNum.length>0})
		]
	}
	
	printData = () => {		// 打印实验号
		const { boardNo } = this.boardData
		let printData = []
		this.state.tableNum.forEach(v => {
			if( $fn.hasObject(v) && v.dtype === 0){
				const printInfo = {
					lb_tpl:boardNo + '-' +v.exp_no,
					spec_code:v.spec_code,
					tpl_code: "barcode",
					kind_name:this.kindName,
					job_id: "感染性核酸岗"
				}
				printData.push(printInfo)
			}
		})
		this.printerRef.printer({ code: 50104, data:printData, loading:false})
	}
	
	saveOtherInfo = (id) => {		// 保存其他信息
		let formValue = this.formRef1.getValue()
		let negative = {}
		let positive = {}
		let device_info = {}
		const { extract, extract_brand, augment, augment_brand, remark} = formValue
		for(let key in formValue){
			if(key.indexOf('negative')!==-1){
				negative[key] = formValue[key]??''
			}
			if((key.indexOf('positive')!==-1)){
				positive[key] = formValue[key]??''
			}
		}
		device_info = { extract:extract??'', extract_brand:extract_brand??'', augment:augment??'', augment_brand:augment_brand??''}
		negative = JSON.stringify(negative)
		positive = JSON.stringify(positive)
		device_info = JSON.stringify(device_info)
		
		const param = {negative, positive,device_info, remark}
		param.board_id = id ? id : this.boardData.id
		$http.submit(null, COVIDUrl+'board/create', { param, loadingText:'保存信息中'}).then(data=>{
			if(!id){
				this.formRef1.reset()
			}else{
				$fn.msg.success('保存成功')
				this.props.onRefresh()
			}
		})
	}
	
	setTable = ({specCode}) => {		// 添加板子标本实验号
		const {hospId,remark,is_audit} = this.props.getValue()
		if(!hospId){
			return $fn.msg.warning('医院必填')
		}else if(hospId === '无'){
			return $fn.msg.warning('该医院不存在，请先添加医院')
		}
		if(!$fn.hasObject(this.boardData)){
			return $fn.msg.warning('请先获取版号')
		}
		const { id, boardNo } = this.boardData
		const repeatSpec = [...new Set(this.bordSpec)].filter(item=>specCode.includes(item))
		if($fn.hasArray(repeatSpec)){
			$fn.toast(`条码【${repeatSpec.join(',')}】已经添加到板子`)
		}
		const specData = specCode.filter((item1) => !repeatSpec.some((item2) => item1 === item2))		// 去掉已添加条码(repeatSpec)
		this.bordSpec = [...this.bordSpec,...specData]
		if($fn.hasArray(specData)){
			specData.forEach((v, i)=>{
				const index = this.state.tableNum.findIndex((v1,i1) => !$fn.hasObject(v1) )
				const tableArr = this.state.tableNum
				tableArr[index] = {dtype:0,
					board_id:id, board_no:boardNo,
					spec_code:v, exp_no:(index+1), 
					sort:index+1, hosp_id:hospId,
					status:is_audit?1:0,remark,
				}
				this.setState({tableNum:tableArr})
			})
		}
		this.props.codeFocus()
	}
	
	clearBoard = () => {	//	清空板子所有信息
		this.negativeIndex = 0
		this.positiveIndex = 0
		this.setState({selectIndex:'',tableNum:new Array(96).fill('')})
		this.bordSpec = []
	}
		
	render(){
		const {selectIndex} = this.state
		const column = new Array(12).fill('')
		const row = new Array(8).fill('')
		row.map((v,i)=> row[i]=String.fromCharCode(i+65) )
		const title = (i) => {
			return <span className='bor1 fxmc' style={{width:18,height:18,borderRadius:'50%',borderColor:'#333'}}>{i}</span>
		}
		const style = {marginRight:20}
		const negativeData =  this.state.tableNum.filter(v => v.dtype === 1)
		negativeData.sort(function(a,b){return a.negaI-b.negaI})
		return (
			<>
				{!this.props.noButton && <div className='fxmj mb10'>
					<div className='fxm'>
						<div>{ SubmitForm.call(this, { labelWidth:'s3', mb:0} ) } </div>
						<div className='ml10'><BtnGroup controls={this.controls1()} /></div>
					</div>
					<div><BtnGroup controls={this.controls()} /></div>
				</div>}
				<div id='printDiv' className='bcf'>
					{/* 表格 */}
					<div className='rel mb10' >
						<div className='fv oxs scrollbar'>
							<div className='fx'>
								<div className='bor1 h30 bcf' style={{minWidth:30,width:30,position:'absolute',top:0,left:0,zIndex:3,borderColor:'#eee'}}></div>
								<div className='fx ex' style={{marginLeft: 30}}>
									{
										column.map((v,i)=>{
											return <div key={v+i} className='ex g3 tc bbor1 rbor1 tbor1 h30' style={{minWidth:86,backgroundColor:'#f7f7f7',borderColor:'#eee'}}>{i+1}</div>
										})
									}
								</div>
							</div>
							
							<div className='fx' style={{height:480}}>
								<div className='fv' style={{width:30,position:'absolute',top:30,left:0,zIndex:2}}>
									{row.map((v,i)=>{
										return <div key={v+i} className='fxmc lbor1 bbor1 rbor1' style={{height:60,width:30,backgroundColor:'#f7f7f7',borderColor:'#eee'}}>{v}</div>
									})}
								</div>
								<div className='ex fv fw ml30 f12'>
									{
										this.state.tableNum.map((v,i)=>{
											return <div key={i} className={'tc rbor1 bbor1 rel oh'} style={{height:60,minWidth:86, backgroundColor:selectIndex === i?'#24948d':(v.warnbc?'#ed5a65':''),color:selectIndex === i?'#fff':'',borderColor:'#eee'}} onClick={(e)=>{
												e.stopPropagation()
												!this.props.noButton && this.setState({selectIndex:i})
											}}>
												<div className='abs_full fv'>
													{v.dtype === 0 &&<><span className='ex fxmc f11' style={{wordBreak:'break-all'}}>{v.spec_code}</span><span className='ex fxmc b'>{v.board_no+'-'+v.exp_no}</span></>}
													{v.dtype === 1 &&<div className='ex fxmc'>
														<span className=''>（-）</span>
														<span className='fxmc bor1' style={{width:16,height:16,borderRadius:'50%',borderColor:selectIndex === i?'#fff':'#333'}}>{v.negaI}</span>
													</div>}
													{v.dtype === 2 &&<div className='ex fxmc'>
														<span className=''>（+）</span>
													</div>}
												</div>
											</div>
										})
									}
								</div>
							</div>
						</div>
					</div>
					{/* 底部表单 */}
					<div>
						<Form className='submit-form' onRef={ref=>this.formRef1=ref} dir='x'>
							{$fn.hasArray(negativeData) &&
								<div className='fxt'>
									<div className='mt5 g3 f12'>阴性质控标注：</div>
									<div className='ex fx fw'>
										{negativeData.map((v,i)=>{
											return <FormItem key={i} tit={title(v.negaI)}	name={`negative${v.negaI}`}	width='200px'		p=''	wrapClassName='mb15' style={style} />
										})}
									</div>
								</div>
							}
							<div className='fxm'>
								<div className='mb15 g3 f12'>阳性质控标注：</div>
								<div className='ex fx'>
									<FormItem tit={<><span>ORF</span><span style={{transform: 'scale(0.7)', marginTop:3}}>1</span><span>ab</span></>}	name='positive1'	width='200px'		p=''	wrapClassName='mb15' style={style} />
									<FormItem tit='N'		name='positive2'	width='200px'		p=''	wrapClassName='mb15'style={style} />
									<FormItem tit='E' 		name='positive3'	width='200px'		p=''	wrapClassName='mb15' style={style} />
								</div>
							</div>
							<div className='fx'>
								<FormItem tit='提取仪' 			name='extract'	width='33%'		p=''	wrapClassName='mb15' style={style} />
								<FormItem tit='提取试剂品牌/批号' name='extract_brand'	width='33%'		p=''	wrapClassName='mb15' style={style} />
								<FormItem tit='扩增仪' 			name='augment'	width='33%'		p=''	wrapClassName='mb15' style={style} />
								<FormItem tit='扩增试剂品牌/批号' name='augment_brand'	width='33%'		p=''	wrapClassName='mb15' style={style} />
							</div>
							<FormItem tit='备注' 	name='remark'  	width='60%'		p=''	 wrapClassName='mb15'	mode='textarea' style={style} />
						</Form>
					</div>
				</div>
				{/* 打印 */}
				<Printer onRef = { ref => this.printerRef = ref } hasBtn = {false} tips = {true}   />
			</>
		)
	}
}

export default Index